using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using MEA.AE_Data;
using MEA.AE_Data.Config;

namespace MEA.AE_BusinessLogic
{
	public class RecManDataLogger : RecManBase
	{
		private const int cPowerLeverDebouncing = 15;

		private const float cCritPowerLever = 90f;

		private ConfigLiveView.ESignals[] LVsignals = new ConfigLiveView.ESignals[16]
		{
			ConfigLiveView.ESignals.e_BPSCD_pFltVal,
			ConfigLiveView.ESignals.e_APSCD_pVal,
			ConfigLiveView.ESignals.e_Prpl_nPrpl,
			ConfigLiveView.ESignals.e_OPSCD_pOutVal,
			ConfigLiveView.ESignals.e_RailCD_pPeak,
			ConfigLiveView.ESignals.e_APPCD_rLinAPP1,
			ConfigLiveView.ESignals.e_CTSCD_tClnt,
			ConfigLiveView.ESignals.e_IATSCD_tAir,
			ConfigLiveView.ESignals.e_BattCD_u,
			ConfigLiveView.ESignals.e_FlPSCD_pFuel,
			ConfigLiveView.ESignals.e_GbTSCD_tGbx,
			ConfigLiveView.ESignals.e_OTSCD_tEngOil,
			ConfigLiveView.ESignals.e_PrplCD_rOut,
			ConfigLiveView.ESignals.e_Eng_stEng,
			ConfigLiveView.ESignals.e_OLSCD_lEngOil,
			ConfigLiveView.ESignals.e_CoEng_rTrq
		};

		public RecManLeadInOut sLeadInLeadOut;

		public string warnToSectorInfo = string.Empty;

		public string warnToLiloInfo = string.Empty;

		public event AddVarDelegate ev_NewVar;

		public RecManDataLogger(BaseService baseService, ref UIGraphWindow gr)
		{
			base.baseService = baseService;
			grLayer = gr;
			AB = baseService.EcuId;
			recordItem_LUT = new LogSignalDatalog[17];
			InitializeRecordItems();
		}

		public RecManDataLogger(BaseService baseService)
		{
			base.baseService = baseService;
			AB = baseService.EcuId;
			recordItem_LUT = new LogSignalDatalog[17];
			InitializeRecordItems();
		}

		public override void SaveToXML(object file)
		{
			throw new NotImplementedException();
		}

		protected override void DecodeData()
		{
			for (int i = 0; i < sLeadInLeadOut.listLeadInOutInfo.Count; i++)
			{
				RecManLeadInOut.SLeadInOutInfo leadInOutData = sLeadInLeadOut.listLeadInOutInfo[i];
				DecodeSession(ref leadInOutData);
			}
		}

		private void DecodeSession(ref RecManLeadInOut.SLeadInOutInfo leadInOutData)
		{
			int interval_ms = 1000;
			int num = 0;
			if (leadInOutData.channelnrs.Count != 16)
			{
				Console.WriteLine("channelnrs.Count != 16; channelnrs.Count = {0};", leadInOutData.channelnrs.Count);
			}
			List<Var> signalIDs = new List<Var>();
			signalIDs.Capacity = 16;
			if (grLayer.UiGraph1.GraphVars == null)
			{
				grLayer.UiGraph1.GraphVars = new ArrayList();
			}
			if (grLayer.UiGraph1.GraphVars_hash == null)
			{
				grLayer.UiGraph1.GraphVars_hash = new Hashtable();
			}
			foreach (ushort channelnr in leadInOutData.channelnrs)
			{
				LogSignalDatalog logSig = (LogSignalDatalog)recordItem_LUT[channelnr - 800];
				string text = string.Format("{0}: {1}", AB, logSig.description);
				lock (grLayer.UiGraph1.GraphVars.SyncRoot)
				{
					if (!grLayer.UiGraph1.GraphVars_hash.Contains(text))
					{
						Var var = new Var(ref logSig, text);
						var.Ecu_Emessage = LVsignals[num++];
						grLayer.UiGraph1.GraphVars.Add(var);
						grLayer.UiGraph1.GraphVars_hash.Add(var.Titel, var);
					}
					signalIDs.Add((Var)grLayer.UiGraph1.GraphVars_hash[text]);
				}
			}
			ExtractSignalValues(ref leadInOutData, ref signalIDs, interval_ms);
		}

		protected override void InitializeRecordItems()
		{
			recordItem_LUT[0] = new LogSignalDatalog(800, "Boost Pressure", ConfigLiveViewBase.ELiveViewSigClass.ePres_hPa, ConfigBase.EStringFormat.e_F0, 0f, 3500f, Color.Red);
			recordItem_LUT[1] = new LogSignalDatalog(801, "Ambient Air Pressure", ConfigLiveViewBase.ELiveViewSigClass.ePres_hPa, ConfigBase.EStringFormat.e_F0, 400f, 1200f, Color.Green);
			recordItem_LUT[2] = new LogSignalDatalog(802, "Propeller Speed", ConfigLiveViewBase.ELiveViewSigClass.eEngN, ConfigBase.EStringFormat.e_F0, 0f, 2500f, Color.Blue);
			recordItem_LUT[3] = new LogSignalDatalog(803, "Engine Oil Pressure", ConfigLiveViewBase.ELiveViewSigClass.ePres_hPa, ConfigBase.EStringFormat.e_F0, 0f, 8000f, Color.YellowGreen);
			recordItem_LUT[4] = new LogSignalDatalog(804, "Rail Pressure", ConfigLiveViewBase.ELiveViewSigClass.ePres_Rail, ConfigBase.EStringFormat.e_F0, 0f, 2000f, Color.Purple);
			recordItem_LUT[5] = new LogSignalDatalog(805, "Power Lever Position", ConfigLiveViewBase.ELiveViewSigClass.ePrc, ConfigBase.EStringFormat.e_F1, 0f, 100f, Color.PowderBlue);
			recordItem_LUT[6] = new LogSignalDatalog(806, "Coolant Temperature", ConfigLiveViewBase.ELiveViewSigClass.eTemp_Cels, ConfigBase.EStringFormat.e_F1, -40f, 160f, Color.PeachPuff);
			recordItem_LUT[7] = new LogSignalDatalog(807, "Intake Air Temperature", ConfigLiveViewBase.ELiveViewSigClass.eTemp_Cels, ConfigBase.EStringFormat.e_F1, -40f, 160f, Color.Orchid);
			recordItem_LUT[8] = new LogSignalDatalog(808, "Battery Voltage", ConfigLiveViewBase.ELiveViewSigClass.eVolt_Batt, ConfigBase.EStringFormat.e_F1, 16f, 36f, Color.GreenYellow);
			recordItem_LUT[9] = new LogSignalDatalog(809, "Fuel Pressure", ConfigLiveViewBase.ELiveViewSigClass.ePres_hPa, ConfigBase.EStringFormat.e_F0, 0f, 8000f, Color.Goldenrod);
			recordItem_LUT[10] = new LogSignalDatalog(810, "Gearbox Oil Temperature", ConfigLiveViewBase.ELiveViewSigClass.eTemp_Cels, ConfigBase.EStringFormat.e_F1, -40f, 160f, Color.Brown);
			recordItem_LUT[11] = new LogSignalDatalog(811, "Engine Oil Temperature", ConfigLiveViewBase.ELiveViewSigClass.eTemp_Cels, ConfigBase.EStringFormat.e_F1, -40f, 160f, Color.Orange);
			recordItem_LUT[12] = new LogSignalDatalog(812, "Prop Actuator - Duty Cycle", ConfigLiveViewBase.ELiveViewSigClass.eDtyCyc, ConfigBase.EStringFormat.e_F1, -100f, 100f, Color.MidnightBlue);
			recordItem_LUT[13] = new LogSignalDatalog(813, "Engine Status", ConfigLiveViewBase.ELiveViewSigClass.eOneToOneBin, ConfigBase.EStringFormat.e_Bin, 0f, 256f, Color.Peru);
			recordItem_LUT[14] = new LogSignalDatalog(814, "Engine Oil Level", ConfigLiveViewBase.ELiveViewSigClass.eLengthMm, ConfigBase.EStringFormat.e_F0, 0f, 100f, Color.HotPink);
			recordItem_LUT[15] = new LogSignalDatalog(815, "Engine Load", ConfigLiveViewBase.ELiveViewSigClass.ePrc, ConfigBase.EStringFormat.e_F1, 0f, 100f, Color.Indigo);
			recordItem_LUT[16] = new LogSignalDatalog(4095, "unkown signal", ConfigLiveViewBase.ELiveViewSigClass.eOneToOne, ConfigBase.EStringFormat.e_X2, 0f, 65535f, Color.Red);
		}

		private void ExtractSignalValues(ref RecManLeadInOut.SLeadInOutInfo leadInOut, ref List<Var> signalIDs, int interval_ms)
		{
			for (int i = 0; i < leadInOut.dataCnt; i++)
			{
				float[] array = leadInOut.DataOfSequenceList[i];
				for (int j = 0; j < signalIDs.Count; j++)
				{
					array[j] = ConfigLiveView.SigClass[(int)signalIDs[j].SigClass].getVal(array[j]);
				}
				leadInOut.DataOfSequenceList[i] = array;
			}
			if (leadInOut.dataCnt <= 0)
			{
				return;
			}
			AddToGraph(ref leadInOut, ref signalIDs, interval_ms);
			lock (grLayer.UiGraph1.GraphVars.SyncRoot)
			{
				for (int k = 0; k < leadInOut.channelnrs.Count; k++)
				{
					foreach (Var graphVar in grLayer.UiGraph1.GraphVars)
					{
						if (graphVar == signalIDs[k])
						{
							graphVar.addLeadOutSessionMarker(leadInOut.dataCnt, leadInOut.TimeStampLiOutOk);
							break;
						}
					}
				}
			}
		}

		protected void AddToGraph(ref RecManLeadInOut.SLeadInOutInfo liloutSeq, ref List<Var> signalIDs, int interval_ms)
		{
			bool flag = true;
			lock (grLayer.UiGraph1.GraphVars.SyncRoot)
			{
				for (int i = 0; i < liloutSeq.channelnrs.Count; i++)
				{
					if (signalIDs[i] == null || liloutSeq.dataCnt <= 0)
					{
						continue;
					}
					Var var = signalIDs[i];
					for (int num = liloutSeq.dataCnt - 1; num >= 0; num--)
					{
						float num2 = 0f;
						float num3 = 0f;
						if (num == liloutSeq.dataCnt - 1)
						{
							foreach (Var graphVar in grLayer.UiGraph1.GraphVars)
							{
								if (graphVar.data.Count > 0 && signalIDs.Contains(graphVar))
								{
									PointF pointF = graphVar.data[graphVar.data.Count - 1];
									if (pointF.X < num3)
									{
										num3 = pointF.X;
									}
								}
							}
							if (var.data.Count > 0)
							{
								if (num3 < var.data[var.data.Count - 1].X - (float)(interval_ms / 1000))
								{
									num2 = num3;
								}
							}
							else
							{
								num2 = num3;
							}
							if (!flag)
							{
								num2 += 1f;
							}
							flag = false;
						}
						bool sessionmarker = false;
						bool newsessionSpace = false;
						if (num == 0)
						{
							sessionmarker = true;
						}
						else if (num == liloutSeq.dataCnt - 1)
						{
							newsessionSpace = true;
						}
						if (num == 0)
						{
							var.Addpoint(liloutSeq.DataTimeStampsList[num], num2, liloutSeq.DataOfSequenceList[num][i], sessionmarker, newsessionSpace);
						}
						else
						{
							var.Addpoint(liloutSeq.DataTimeStampsList[num], 0f, liloutSeq.DataOfSequenceList[num][i], sessionmarker, newsessionSpace);
						}
					}
				}
			}
		}

		protected override void AddToGraph()
		{
			throw new NotImplementedException();
		}

		public override void ViewFromHexDump(ref List<RecManSector> sectors, RecManStatus status, string fileCreation)
		{
			sectorsRaw_AL.Clear();
			dataPayload.Clear();
			int num = -1;
			List<int> list = new List<int>();
			bool flag = true;
			for (int i = 0; i < sectors.Count; i++)
			{
				RecManSector recManSector = sectors[i];
				flag = true;
				if (recManSector.ID <= 15 || recManSector.ID >= 140)
				{
					continue;
				}
				for (int j = 0; j < list.Count; j++)
				{
					if (list[j] == recManSector.ID)
					{
						flag = false;
						break;
					}
				}
				if (flag)
				{
					list.Add(recManSector.ID);
					switch (recManSector.Type)
					{
					case RecManSector_Type.active:
						num = sectorsRaw_AL.Count;
						sectorsRaw_AL.Add(recManSector);
						break;
					case RecManSector_Type.locked:
						sectorsRaw_AL.Add(recManSector);
						break;
					case RecManSector_Type.fullNotLocked:
						sectorsRaw_AL.Add(recManSector);
						warnToSectorInfo += string.Format("\\line ECU-{0}: Sector Nr. {1} is Type: {2}", AB, recManSector.ID, recManSector.Type);
						break;
					case RecManSector_Type.unknown:
						warnToSectorInfo += string.Format("\\line ECU-{0}: Sector Nr. {1} is Type: \"Unknown\"", AB, recManSector.ID);
						break;
					}
					if (!recManSector.ChkOk)
					{
						warnToSectorInfo += string.Format("\\line ECU-{0}: Sector Nr. {1} has a \"Checksumm Error\". Deleted", AB, recManSector.ID);
					}
				}
				else
				{
					warnToSectorInfo += string.Format("\\line ECU-{0}: Sector Nr. {1} has a \"Duplicate Error\". Deleted", AB, recManSector.ID);
				}
			}
			sectors.Clear();
			if (num == -1)
			{
				warnToSectorInfo = "\\line ECU-{0}: No Active sector found.";
			}
			if (sectorsRaw_AL.Count == 0)
			{
				throw new Exception("Error in XML import");
			}
			if (num == -1)
			{
				num = sectorsRaw_AL.Count - 1;
			}
			sectorsRaw_AL.Sort();
			SortSectorsRingBuffer(ref sectorsRaw_AL, num);
			dataPayload.Capacity = 65528 * sectorsRaw_AL.Count;
			for (int k = 0; k < sectorsRaw_AL.Count; k++)
			{
				Ev_ProgressStep_call(string.Format("Concatenate payload data sector {0} to stream", sectorsRaw_AL[k].ID));
				dataPayload.AddRange(sectorsRaw_AL[k].DataPayld);
			}
			sectorsRaw_AL.Clear();
			string fileTime = fileCreation;
			sLeadInLeadOut = new RecManLeadInOut(ref dataPayload, ref fileTime, AB);
			dataPayload.Clear();
			string aB = string.Format("ECU {0}:  ", AB);
			if (sLeadInLeadOut != null)
			{
				if (sLeadInLeadOut.listLeadInOutInfo != null)
				{
					if (sLeadInLeadOut.listLeadInOutInfo.Count > 0)
					{
						for (int l = 0; l < sLeadInLeadOut.listLeadInOutInfo.Count; l++)
						{
							RecManLeadInOut.SLeadInOutInfo sLeadInOutInfo = sLeadInLeadOut.listLeadInOutInfo[l];
							if (sLeadInOutInfo.sLiLoNote != null)
							{
								warnToLiloInfo += sLeadInOutInfo.sLiLoNote;
							}
						}
						for (int num2 = sLeadInLeadOut.listLeadInOutInfo.Count - 1; num2 >= 0; num2--)
						{
							RecManLeadInOut.SLeadInOutInfo sLeadInOutInfo = sLeadInLeadOut.listLeadInOutInfo[num2];
							if (sLeadInOutInfo.vLiLoStatus == RecManLeadInOut.SLeadInOutInfo.ELiLoStatus.eNoUsableLiLo)
							{
								sLeadInLeadOut.listLeadInOutInfo.RemoveAt(num2);
							}
							else if (sLeadInOutInfo.dataCnt < 2)
							{
								TimeSpan timeSpan = new TimeSpan(0, 0, 1);
								if (sLeadInOutInfo.dataCnt == 0)
								{
									RecManLeadInOut.SLeadInOutInfo sLeadInOutInfo2 = ((num2 != sLeadInLeadOut.listLeadInOutInfo.Count - 1) ? sLeadInLeadOut.listLeadInOutInfo[num2 + 1] : sLeadInLeadOut.listLeadInOutInfo[num2 - 1]);
									if (sLeadInOutInfo2.dataCnt > 1)
									{
										sLeadInOutInfo.DataOfSequenceList.Add(sLeadInOutInfo2.DataOfSequenceList[sLeadInOutInfo2.DataOfSequenceList.Count - 2]);
										sLeadInOutInfo.DataOfSequenceList.Add(sLeadInOutInfo2.DataOfSequenceList[sLeadInOutInfo2.DataOfSequenceList.Count - 2]);
									}
									sLeadInOutInfo.DataTimeStampsList.Add(sLeadInOutInfo.LeadInTime);
									sLeadInOutInfo.DataTimeStampsList.Add(sLeadInOutInfo.LeadInTime + timeSpan);
								}
								else
								{
									sLeadInOutInfo.DataOfSequenceList.Add(sLeadInOutInfo.DataOfSequenceList[0]);
									sLeadInOutInfo.DataTimeStampsList.Add(sLeadInOutInfo.DataTimeStampsList[0] + timeSpan);
								}
								sLeadInOutInfo.dataCnt = sLeadInOutInfo.DataOfSequenceList.Count;
								sLeadInLeadOut.listLeadInOutInfo[num2] = sLeadInOutInfo;
							}
						}
						DecodeData();
					}
					else
					{
						Ev_AddConsole_call("The Recordind does not include eny Data!!!", Color.Red, aB);
						MessageBox.Show("The Recordind does not include eny Data!", string.Format("{0} Warning", ConfigData.WizardSwName));
					}
				}
				else
				{
					Ev_AddConsole_call("The Recordind does not include eny Data!!!", Color.Red, aB);
					MessageBox.Show("The Recordind does not include eny Data!", string.Format("{0} Warning", ConfigData.WizardSwName));
				}
			}
			else
			{
				Ev_AddConsole_call("The Recordind can not be readet!!!", Color.Red, aB);
				MessageBox.Show("The Recordind can not be readet!", string.Format("{0} Warning", ConfigData.WizardSwName));
			}
		}

		public string testPowLev(ref Xml_Log.CXmlFileLogInfo fileInfo)
		{
			string text = string.Empty;
			if (fileInfo != null)
			{
				int num = 5;
				int num2 = 0;
				int num3 = 0;
				bool flag = true;
				DateTime dateTime = default(DateTime);
				for (int i = 0; i < sLeadInLeadOut.listLeadInOutInfo.Count; i++)
				{
					RecManLeadInOut.SLeadInOutInfo sLeadInOutInfo = sLeadInLeadOut.listLeadInOutInfo[i];
					if (sLeadInOutInfo.DataOfSequenceList.Count <= 300)
					{
						continue;
					}
					num2 = 0;
					num3 = 0;
					flag = true;
					for (int j = 0; j < sLeadInOutInfo.DataOfSequenceList.Count; j++)
					{
						float[] array = sLeadInOutInfo.DataOfSequenceList[j];
						if (array[num] > 90f)
						{
							if (num2 == 0)
							{
								dateTime = sLeadInOutInfo.DataTimeStampsList[j];
							}
							else if (num2 > 300 && flag)
							{
								string[] array2 = string.Format("{0}", dateTime).Split(' ');
								text += string.Format("\\line ECU-{3} Time Period: \\b {0} - {1} \\b0 : at {2}; Engine overload for to long Time\n", sLeadInOutInfo.LeadInTime, sLeadInOutInfo.LeadOutTime, array2[1], AB);
								flag = false;
							}
							num2++;
							num3 = 0;
						}
						else if (num2 > 0)
						{
							if (num3 > 15)
							{
								num2 = 0;
								num3 = 0;
								flag = true;
							}
							else
							{
								num3++;
							}
						}
					}
				}
			}
			return text;
		}
	}
}
